const app = getApp()
const db = wx.cloud.database(); //初始化数据库
Page({
    /**
     * 页面的初始数据
     */
    data: {
        imgbox1: [],
        imgbox2: [], //选择图片
        fileIDs: [], //上传云存储后的返回值
    },

    onLoad: function (options) {
        //获取已有附件
        if (app.globalData.type == 1) {
            db.collection('user').where({
                openid: app.globalData.userid
            }).get({
                success: res => {
                    console.log(res)
                    if (res.data[0].attachment) {
                        var imgbox1 = res.data[0].attachment
                        this.setData({
                            imgbox1: imgbox1
                        })
                    }
                }
            })
        } else if (app.globalData.type == 2) {
            db.collection('user2').where({
                openid: app.globalData.userid
            }).get({
                success: res => {
                    console.log(res)
                    if (res.data[0].attachment) {
                        var imgbox1 = res.data[0].attachment
                        this.setData({
                            imgbox1: imgbox1
                        })
                    }
                }
            })
        } else if (app.globalData.type == 3) {
            db.collection('user3').where({
                openid: app.globalData.userid
            }).get({
                success: res => {
                    console.log(res)
                    if (res.data[0].attachment) {
                        var imgbox1 = res.data[0].attachment
                        this.setData({
                            imgbox1: imgbox1
                        })
                    }
                }
            })
        }
    },
    // 删除照片 &&
    imgDelete1: function (e) {
        let index = e.currentTarget.dataset.deindex;
        let imgbox2 = this.data.imgbox2;
        imgbox2.splice(index, 1)
        this.setData({
            imgbox2: imgbox2
        });
    },
    // 选择图片 &&&
    addPic1: function (e) {
        var imgbox2 = this.data.imgbox2;
        console.log('选择图片imgbox2：', imgbox2)
        var that = this;
        wx.chooseMedia({
            count: 9,
            mediaType: 'image',
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                console.log('成功', res)
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = [];
                for (let i = 0; i < res.tempFiles.length; i++) {
                    tempFilePaths[i] = res.tempFiles[i].tempFilePath;
                }
                if (imgbox2.length == 0) {
                    imgbox2 = tempFilePaths
                } else {
                    imgbox2 = imgbox2.concat(tempFilePaths);
                }
                that.setData({
                    imgbox2: imgbox2
                });

            }
        })
    },

    //图片
    imgbox1: function (e) {
        let index = e.currentTarget.dataset.deindex;
        let imgbox1 = this.data.imgbox1;
        wx.previewImage({
            urls: [imgbox1[index]],
        })
    },
    //图片
    imgbox2: function (e) {
        let index = e.currentTarget.dataset.deindex;
        let imgbox2 = this.data.imgbox2;
        wx.previewImage({
            urls: [imgbox2[index]],
        })
    },


    //发布按钮
    fb: function (e) {
        console.log(this.data.imgbox2)
        if (!this.data.imgbox2.length) {
            wx.showToast({
                icon: 'none',
                title: '未选择附件图片'
            });
        } else {
            //上传图片到云存储
            wx.showLoading({
                title: '上传中',
            })
            let promiseArr = [];
            console.log('1:', this.data.imgbox2)
            var imgbox3 = this.data.imgbox2;
            for (let i = 0; i < imgbox3.length; i++) {
                promiseArr.push(new Promise((reslove, reject) => {
                    let item = imgbox3[i];
                    let suffix = /\.\w+$/.exec(item)[0]; //正则表达式返回文件的扩展名
                    let len = 6;
                    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; //排除了一些混淆随机字符
                    var maxPos = chars.length;
                    var rand = '';
                    for (let x = 0; x < len; x++) {
                        rand += chars.charAt(Math.floor(Math.random() * maxPos));
                    }
                    wx.cloud.uploadFile({
                        cloudPath: `附件图片/` + rand + suffix, // 上传至云端的路径
                        filePath: item, // 小程序临时文件路径
                        success: res => {
                            this.setData({
                                fileIDs: this.data.fileIDs.concat(res.fileID)
                            });
                            console.log(res.fileID) //输出上传后图片的返回地址
                            reslove();
                            wx.hideLoading();
                            wx.showToast({
                                title: "上传成功",
                            })
                        },
                        fail: res => {
                            wx.hideLoading();
                            wx.showToast({
                                title: "上传失败",
                            })
                        }

                    })
                }));
            }
            Promise.all(promiseArr).then(res => { //等数组都做完后做then方法
                console.log("图片上传完成后再执行")
                console.log(this.data.fileIDs)
                var that = this;
                var imgbox4 = that.data.imgbox1;
                if (imgbox4.length == 0) {
                    imgbox4 = that.data.fileIDs
                } else {
                    imgbox4 = imgbox4.concat(that.data.fileIDs);
                }
                wx.cloud.callFunction({
                    name: 'userfj',
                    data: {
                        type:app.globalData.type,
                        openid: app.globalData.userid,
                        attachment: imgbox4,
                    },
                    success: resss => {
                        console.log(resss)
                    },
                    fail: resss => {
                        console.log(resss)
                    }
                })
                setTimeout(() => {
                    wx.redirectTo({
                        url: '/pages/scfj/scfj'
                    })
                }, 80);

            })

        }
    },

})